package com.chase.chasecat.filter;

import com.chase.chasecat.entity.UserEntity;
import com.chase.chasecat.utils.JwtHelper;
import com.chase.chasecat.utils.UserUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 如果是登录接口直接放行
        if (httpServletRequest.getRequestURI().equals("/login")){
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        // 获取token
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // 如果没有token则抛异常
            throw new RuntimeException("禁止访问");
        }
        // 从redis中获取用户信息
        UserEntity user = (UserEntity) redisTemplate.opsForValue().get(token);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户未登录");
        }
        // 存入本地缓存中
        UserUtil.setUser(user);

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
